"""玩家模块"""
import board
import random


class Player:
    """玩家类"""

    def __init__(self, name):
        """初始化玩家"""
        self.name = name  # 玩家名字
        self.score = 0  # 玩家得分
        self.chess = None  # 玩家的棋子

    def move(self, _board):
        """玩家落一个棋子到棋盘上"""
        index = -1
        while index not in _board.moveable_list:
            try:
                index = int(input('请"%s"输入落子位置:%s' % (self.name, _board.moveable_list)))
            except ValueError:
                print('请输入正确的数字')

        _board.move_down(index, self.chess)


class AIPlayer(Player):
    """AI智能玩家"""

    def move(self, _board):
        """智能落子:AI能够在棋盘剩余的可用位置里选择一个，并落子"""
        print('%s 正在思考落子位置' % self.name)

        #1.判断是否有必胜位置
        for index in _board.moveable_list:
            if _board.is_win(self.chess,index):
                _board.move_down(index,self.chess)
                return

        #2.判断是否有必救位置
        other_chess = 'O' if self.chess =='X' else 'X'
        for index in _board.moveable_list:
            if _board.is_win(other_chess,index):
                _board.move_down(index,self.chess)
                return

        #3.根据子力价值选择落子位置
        index = -1
        #  没有落子的角位置列表,从角位置集合与棋盘可用位置集合取交集
        corner_list = list({0, 2, 6, 8}.intersection(_board.moveable_list))
        #  没有落子的边位置列表
        edges_list = list({0, 2, 6, 8}.intersection(_board.moveable_list))

        if 4 in _board.moveable_list:
            index = 4
        elif corner_list:
            #  随机在剩余的可用位置里选一个下标
            index = random.choice(corner_list)
        elif edges_list:
            index = random.choice(edges_list)

        #  在选择的下标上落子
        _board.move_down(index, self.chess)


if __name__ == '__main__':
    player1 = Player('玩家1')
    player1.chess = 'X'
    print(player1.name)
    print(player1.score)
    print(player1.chess)

    # 测试玩家落子功能
    board = board.Board()

    while not board.is_win(player1.chess):
        player1.move(board)
        board.show_board()
